package com.detroitchow2;

import java.util.ArrayList;

import com.detroitchow2.api.IStoreServiceObserver;
import com.detroitchow2.layout.StoresArrayAdapter;
import com.detroitchow2.util.LogUtil;
import com.detroitchow2.vo.StoreVO;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;



public class MainActivity extends Activity
implements OnTouchListener, OnClickListener, OnItemClickListener, IStoreServiceObserver
{

  private ListView storesListView;
  private LinearLayout layoutTags;
  private StoreService storeService;
  private ArrayList<StoreVO> stores;
  private ProgressDialog pd;
  private StoresArrayAdapter storesArrayAdapter;
  private ArrayList<String> tags;
  private Button _btnTag;
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    storesListView = (ListView) this.findViewById(R.id.lvStores);
    layoutTags = (LinearLayout) findViewById(R.id.layoutTags); // Categories section
    storeService = ((StoreService)getApplicationContext()); // Singelton that provides the activity the data it needs
    try
    {
      stores = storeService.getStoresList();
    }catch(Exception e)
    {
      stores = null;
    }
    
    if(stores == null)
    {
      storeService.registerUpdateStoresObserver(this);
      callProgressBar();
      storeService.initStores();
    }else
    {
      onStoreManagerUpdate();
    }
    
    
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    ActionBar actionBar = getActionBar(); // || getActionBar();
    actionBar.setIcon(getResources().getDrawable(R.drawable.action_bar_icon));
    actionBar.setTitle("");
    menu.add(Menu.NONE, 34343, menu.size(), "About"); 
    return true;
    
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) 
  {
    Intent intent;
    LogUtil.log("onOptionsItemSelected", "Click event id: " + item.getItemId());
    switch (item.getItemId()) {
        case R.id.refresh:
          
          executeRefresh();
          return true;
          
        case R.id.search:
          
          intent = new Intent(this, SearchActivity.class);
          startActivityForResult(intent, 0);
          return true;
          
        case R.id.location:
          
          intent = new Intent(this,  MapScreen.class);
          intent.putExtra(AppIntent.MAP_INTENT, AppIntent.LOCATION);
          startActivityForResult(intent, 0);
          return true;
          
        case 34343:
          
          intent = new Intent(this,  AboutActivity.class);
          startActivityForResult(intent, 0);
          return true;
       
          
        default:
            return super.onOptionsItemSelected(item);
    }
  }
  
  private void executeRefresh()
  {
    storeService.registerUpdateStoresObserver(this);
    layoutTags.removeAllViewsInLayout();
    storesListView.removeAllViewsInLayout();
    storesListView.refreshDrawableState();
    callProgressBar();
    storeService.refreshStores();
  }
  
  public void onClick(View v) 
  {
    /// handle Actionbar
  }
  
  

  public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
    // TODO Auto-generated method stub
    
    /*
    StoreVO store =  stores.get(index);
    Intent myIntent = new Intent(this, StoreViewActivity.class);
    myIntent.putExtra(StoreService.SELECTED_STORE_KEY, store);
    startActivityForResult(myIntent, 0);
    */
    
    
    int selectedStoreId =  stores.get(index).mapGroupId ;
    int realStoreId =  stores.get(index).storeId ;
    Intent myIntent = new Intent(this, MapScreen.class);
    myIntent.putExtra(AppIntent.MAP_INTENT, MapIntent.SELECT_STORE);
    myIntent.putExtra(StoreService.SELECTED_STORE_KEY, selectedStoreId);
    myIntent.putExtra(StoreService.SELECTED_STORE_OVERRIDE, realStoreId);
    startActivityForResult(myIntent, 0);
    
  }
  
@Override
  protected void onResume()
  {
    super.onResume();
    try
    {
    
      Bundle bundle = getIntent().getExtras();
      if(bundle.containsKey(AppIntent.REFRESH))
      {
        executeRefresh();
      }
      
    }catch(Exception e)
    {
      
    }
    
  }

//request to fetch stores is complete layout the Tags and Stores List
 public void onStoreManagerUpdate() 
 {
   LogUtil.log("Main",  "onStoreManagerUpdate");
   storeService.unRegisterUpdateStoresObserver(this);
   tags = storeService.getTags();
   
   
   // Layout the Tags onto the screen
   if(tags != null){
     for(String tag: tags)
     {
       LogUtil.log("Main",  "onStoreManagerUpdate tags : " + tag);
       _btnTag = (Button)getLayoutInflater().inflate(R.layout.linkitem, null);
       _btnTag.setText(tag);
       _btnTag.setTag(tag);
       _btnTag.setOnClickListener(this);
       _btnTag.setOnTouchListener(this);
       ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(tag.length() * 25, 75);
       _btnTag.setLayoutParams(layoutParams);
       layoutTags.addView(_btnTag);
     }
   } else
   {
     LogUtil.log("Main",  "onStoreManagerUpdate tags is null");
   }
   
   if(pd != null)
     pd.dismiss();
   
   stores = storeService.getStoresList();
   /* 
     if(stores == null)
     LogUtil.log("Main",  "onStoreManagerUpdate stores is null");
   else
     LogUtil.log("Main",  "onStoreManagerUpdate stores is not null: " + stores.size());
     */
   refreshDirectory();
 }
  
  public void refreshDirectory() 
  {
    LogUtil.log("Main refreshDirectory", "Stores Size: " + stores.size());
    storesArrayAdapter = 
        new StoresArrayAdapter
        (
            this, 
            R.layout.directoryitem, 
            R.id.txtstoretitle, 
            stores
         );
    if(storesArrayAdapter != null)
    {
      storesListView.setAdapter(storesArrayAdapter);
      storesListView.setTextFilterEnabled(true);
      storesListView.setOnItemClickListener(this);
    }
  }
  
  public boolean onTouch(View v, MotionEvent event) 
  {
    if (v.getTag() != null){
      // handles touch event for the Categories
      if(v.getTag().toString().toUpperCase().equals(StoreService.ALL_TAG))
        stores = storeService.getStoresList();
       else
         stores = storeService.getStoresList((String)v.getTag());
      refreshDirectory();
    }
    return false;
  }
  
  private void callProgressBar()
  {
    pd = ProgressDialog.show
        (
            this, 
            "Working..",
            "Refreshing the Detroit Chow list", 
            true,
            false
        );
  }

}
